﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using Ninject;
using FriendlyURL.Web.Domain.Abstract;
using FriendlyURL.Web.Domain.Models;

namespace FriendlyURL.Web.UI.Infrastructure
{
    public class AccountRoleProvider : RoleProvider
    {
        [Inject]
        public IUserRepository UserRepository { get; set; }

        #region UnImplemented RoleProvider Overrides
        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override string ApplicationName
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public override void CreateRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            throw new NotImplementedException();
        }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            throw new NotImplementedException();
        }

        public override string[] GetAllRoles()
        {
            throw new NotImplementedException();
        }

        public override string[] GetUsersInRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override bool RoleExists(string roleName)
        {
            throw new NotImplementedException();
        }

        #endregion

        public override string[] GetRolesForUser(string userName)
        {
            return UserRepository.GetRolesForUser(userName);
        }

        public override bool IsUserInRole(string userName, string roleName)
        {
            if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(roleName))
            {
                return false;
            }

            User user = UserRepository.GetUserByLoginID(userName);
            string[] userRoles = UserRepository.GetRolesForUser(userName);

            if (!UserRepository.UserExists(user))
            {
                return false;
            }

            if (userRoles == null)
            {
                return false;
            }

            return userRoles.Contains(roleName, StringComparer.OrdinalIgnoreCase);
        }
    }
}